import json
import os
import datetime
from jinja2 import Environment, FileSystemLoader
from typing import Dict, List, Tuple

class ReportGenerator:
    """轮回报告生成器，用于生成游戏轮回总结报告"""
    
    def __init__(self, report_dir: str = "../../数据管理/narrative_archive/reports",
                 template_dir: str = "../templates/reports"):
        """初始化报告生成器"""
        self.report_dir = report_dir
        os.makedirs(self.report_dir, exist_ok=True)
        
        self.template_dir = template_dir
        os.makedirs(self.template_dir, exist_ok=True)
        
        # 初始化Jinja2模板环境
        self.env = Environment(
            loader=FileSystemLoader(self.template_dir),
            trim_blocks=True,
            lstrip_blocks=True
        )
        
        # 确保默认模板存在
        self._ensure_default_template()
    
    def _ensure_default_template(self):
        """确保默认模板存在"""
        default_template = "轮回报告模板.j2"
        default_path = os.path.join(self.template_dir, default_template)
        
        if not os.path.exists(default_path):
            with open(default_path, "w", encoding="utf-8") as f:
                f.write("""# 翁法罗斯传奇 - 第{{ cycle_number }}轮回报告
生成时间: {{ generate_time }}

## 轮回概要
- 持续时间: {{ summary.duration }}
- 参与因子: {{ summary.factors_count }} 位
- 胜利方: {{ summary.winner }}
- 主要事件: {{ summary.key_event }}

## 因子表现
{% for factor in factors %}
### {{ factor.name }} ({{ factor.id }})
- 战斗场次: {{ factor.battles }}
- 胜利场次: {{ factor.wins }}
- 贡献度: {{ factor.contribution }}
- 成长值: {{ factor.growth }}
- 特殊成就: {{ factor.achievements | join(', ') or '无' }}
{% endfor %}

## 关键事件记录
{% for event in key_events %}
- {{ event.time }}: {{ event.description }}
{% endfor %}

## 轮回评价
{{ evaluation.overall }}

优势分析:
{{ evaluation.strengths | join('\n- ') }}

改进建议:
{{ evaluation.suggestions | join('\n- ') }}

## 下一轮回预测
{{ prediction }}
""")
    
    def generate_cycle_report(self, cycle_data: Dict, template_name: str = "轮回报告模板.j2") -> Tuple[str, str]:
        """
        生成轮回报告
        :param cycle_data: 轮回数据
        :param template_name: 模板名称
        :return: (报告内容, 报告文件路径)
        """
        # 准备报告数据
        report_data = {
            "cycle_number": cycle_data.get("cycle_number", 1),
            "generate_time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "summary": cycle_data.get("summary", {}),
            "factors": cycle_data.get("factors", []),
            "key_events": cycle_data.get("key_events", []),
            "evaluation": cycle_data.get("evaluation", {
                "overall": "未评价",
                "strengths": [],
                "suggestions": []
            }),
            "prediction": cycle_data.get("prediction", "无法预测")
        }
        
        # 渲染模板
        try:
            template = self.env.get_template(template_name)
            report_content = template.render(**report_data)
        except Exception as e:
            raise Exception(f"报告生成失败: {str(e)}")
        
        # 保存报告
        report_filename = f"cycle_{report_data['cycle_number']}_{datetime.datetime.now().strftime('%Y%m%d')}.md"
        report_path = os.path.join(self.report_dir, report_filename)
        
        with open(report_path, "w", encoding="utf-8") as f:
            f.write(report_content)
        
        return report_content, report_path
    
    def generate_summary_report(self, cycles: List[int]) -> Tuple[str, str]:
        """生成多轮回汇总报告"""
        # 收集多轮回数据
        cycle_reports = []
        for cycle_num in cycles:
            # 查找对应轮回的报告
            found = False
            for filename in os.listdir(self.report_dir):
                if filename.startswith(f"cycle_{cycle_num}_") and filename.endswith(".md"):
                    with open(os.path.join(self.report_dir, filename), "r", encoding="utf-8") as f:
                        cycle_reports.append({
                            "number": cycle_num,
                            "content": f.read()
                        })
                    found = True
                    break
            if not found:
                cycle_reports.append({
                    "number": cycle_num,
                    "content": f"第{cycle_num}轮回报告不存在"
                })
        
        # 生成汇总报告
        summary_data = {
            "cycles": cycles,
            "generate_time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "cycle_reports": cycle_reports
        }
        
        # 使用汇总模板
        summary_template = "汇总报告模板.j2"
        summary_template_path = os.path.join(self.template_dir, summary_template)
        
        if not os.path.exists(summary_template_path):
            with open(summary_template_path, "w", encoding="utf-8") as f:
                f.write("""# 翁法罗斯传奇 - 多轮回汇总报告
生成时间: {{ generate_time }}
涵盖轮回: {{ cycles | join(', ') }}

{% for report in cycle_reports %}
## 第{{ report.number }}轮回概要
{{ report.content.split('## 轮回概要')[1].split('## 因子表现')[0] }}
{% endfor %}

## 轮回对比分析
请在此处添加多轮回对比分析...
""")
        
        try:
            template = self.env.get_template(summary_template)
            report_content = template.render(** summary_data)
        except Exception as e:
            raise Exception(f"汇总报告生成失败: {str(e)}")
        
        # 保存汇总报告
        report_filename = f"summary_{'_'.join(map(str, cycles))}_{datetime.datetime.now().strftime('%Y%m%d')}.md"
        report_path = os.path.join(self.report_dir, report_filename)
        
        with open(report_path, "w", encoding="utf-8") as f:
            f.write(report_content)
        
        return report_content, report_path